<template>
  <div class="activity-list-container">
    <div class="search-filter-section">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="活动名称">
          <el-input v-model="queryParams.name" placeholder="请输入活动名称" clearable @keyup.enter="handleSearch"/>
        </el-form-item>
        <el-form-item label="活动类型">
          <el-select v-model="queryParams.typeId" placeholder="请选择活动类型" clearable>
            <el-option
              v-for="item in activityTypes"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动状态">
          <el-select v-model="queryParams.status" placeholder="请选择活动状态" clearable>
            <el-option label="规划中" :value="0" />
            <el-option label="报名中" :value="1" />
            <el-option label="等待中" :value="2" />
            <el-option label="进行中" :value="3" />
            <el-option label="已结束" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="activity-list">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="activity in activityList" :key="activity.id">
          <el-card class="activity-card" shadow="hover">
            <template #header>
              <div class="activity-header">
                <span class="activity-title" @click="goToDetail(activity.id)">{{ activity.name }}</span>
                <el-tag :type="getStatusType(activity.status)" size="small">{{ getStatusText(activity.status) }}</el-tag>
              </div>
            </template>
            <div class="activity-content">
              <div class="activity-image" @click="goToDetail(activity.id)">
                <img :src="activity.imageUrl || 'https://picsum.photos/id/42/400/200'" alt="活动图片" />
              </div>
              <div class="activity-info">
                <div class="info-item">
                  <el-icon><LocationFilled /></el-icon>
                  <span>{{ activity.location }}</span>
                </div>
                <div class="info-item">
                  <el-icon><Clock /></el-icon>
                  <span>{{ formatTime(activity.startTime) }} - {{ formatTime(activity.endTime) }}</span>
                </div>
                <div class="info-item">
                  <el-icon><User /></el-icon>
                  <span>已报名: {{ activity.registeredNumber }}/{{ activity.totalNumber }}</span>
                </div>
                <div class="info-item">
                  <el-icon><Timer /></el-icon>
                  <span>活动时长: {{ activity.duration }}小时</span>
                </div>
                <div class="info-item">
                  <el-icon><OfficeBuilding /></el-icon>
                  <span>组织: {{ activity.organizationName }}</span>
                </div>
              </div>
              <div class="activity-actions">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="goToDetail(activity.id)"
                >查看详情</el-button>
                <el-button 
                  v-if="activity.status === 1 && !activity.isRegistered" 
                  type="success" 
                  size="small" 
                  @click="handleRegister(activity.id)"
                >报名</el-button>
                <el-button 
                  v-if="activity.isRegistered" 
                  type="danger" 
                  size="small" 
                  @click="handleCancelRegistration(activity.id)"
                >取消报名</el-button>
                <el-button 
                  :type="activity.isCollected ? 'warning' : 'info'" 
                  size="small" 
                  @click="toggleCollect(activity)"
                >
                  <el-icon><Star /></el-icon>
                  <span>{{ activity.isCollected ? '已收藏' : '收藏' }}</span>
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.current"
        v-model:page-size="queryParams.size"
        :page-sizes="[8, 16, 24, 32]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { pageActivities } from '@/api/activity';
import { registerActivity, cancelRegistration, isUserRegistered } from '@/api/registration';
import { addCollection, cancelCollection, isUserCollected } from '@/api/collection';
import { formatDateTime } from '@/utils/format';
import { LocationFilled, Clock, User, Timer, OfficeBuilding, Star } from '@element-plus/icons-vue';

const router = useRouter();

// 活动类型列表
const activityTypes = ref([
  { id: 1, name: '创新创业' },
  { id: 2, name: '文体活动' },
  { id: 3, name: '技能特长' },
  { id: 4, name: '公益服务' },
  { id: 5, name: '其他' }
]);

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 8,
  name: '',
  typeId: '',
  status: ''
});

const total = ref(0);
const activityList = ref([]);
const loading = ref(false);

// 获取活动列表
const getList = async () => {
  try {
    loading.value = true;
    const response = await pageActivities(
      queryParams.current,
      queryParams.size,
      {
        name: queryParams.name,
        typeId: queryParams.typeId,
        status: queryParams.status
      }
    );
    
    activityList.value = response.data.records;
    total.value = response.data.total;
    
    // 检查用户是否已报名和收藏每个活动
    for (const activity of activityList.value) {
      const [registrationRes, collectionRes] = await Promise.all([
        isUserRegistered(activity.id),
        isUserCollected(activity.id)
      ]);
      activity.isRegistered = registrationRes.data;
      activity.isCollected = collectionRes.data;
    }
  } catch (error) {
    console.error('获取活动列表失败', error);
    ElMessage.error('获取活动列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  queryParams.current = 1;
  getList();
};

// 重置查询
const resetQuery = () => {
  queryParams.name = '';
  queryParams.typeId = '';
  queryParams.status = '';
  handleSearch();
};

// 分页大小变更
const handleSizeChange = (size) => {
  queryParams.size = size;
  getList();
};

// 分页页码变更
const handleCurrentChange = (page) => {
  queryParams.current = page;
  getList();
};

// 前往活动详情页
const goToDetail = (id) => {
  router.push(`/activity/detail/${id}`);
};

// 报名活动
const handleRegister = async (activityId) => {
  try {
    await registerActivity(activityId);
    ElMessage.success('报名成功');
    getList(); // 刷新列表
  } catch (error) {
    console.error('报名失败', error);
    ElMessage.error(error.message || '报名失败');
  }
};

// 取消报名
const handleCancelRegistration = async (activityId) => {
  try {
    await ElMessageBox.confirm('确定要取消报名吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    await cancelRegistration(activityId);
    ElMessage.success('已取消报名');
    getList(); // 刷新列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消报名失败', error);
      ElMessage.error(error.message || '取消报名失败');
    }
  }
};

// 切换收藏状态
const toggleCollect = async (activity) => {
  try {
    if (activity.isCollected) {
      await cancelCollection(activity.id);
      activity.isCollected = false;
      ElMessage.success('已取消收藏');
    } else {
      await addCollection(activity.id);
      activity.isCollected = true;
      ElMessage.success('收藏成功');
    }
  } catch (error) {
    console.error('操作失败', error);
    ElMessage.error(error.message || '操作失败');
  }
};

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'info',    // 规划中
    1: 'success', // 报名中
    2: 'warning', // 等待中
    3: 'primary', // 进行中
    4: 'danger'   // 已结束
  };
  return statusMap[status] || 'info';
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '规划中',
    1: '报名中',
    2: '等待中',
    3: '进行中',
    4: '已结束'
  };
  return statusMap[status] || '未知';
};

// 格式化时间
const formatTime = (time) => {
  return formatDateTime(time);
};

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.activity-list-container {
  padding: 20px 0;
  
  .search-filter-section {
    margin-bottom: 20px;
    
    .search-form {
      display: flex;
      flex-wrap: wrap;
    }
  }
  
  .activity-list {
    margin-bottom: 20px;
    
    .activity-card {
      margin-bottom: 20px;
      transition: transform 0.3s;
      
      &:hover {
        transform: translateY(-5px);
      }
      
      .activity-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .activity-title {
          font-size: 16px;
          font-weight: bold;
          cursor: pointer;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          
          &:hover {
            color: #409EFF;
          }
        }
      }
      
      .activity-content {
        .activity-image {
          height: 150px;
          overflow: hidden;
          border-radius: 4px;
          margin-bottom: 10px;
          cursor: pointer;
          
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s;
            
            &:hover {
              transform: scale(1.05);
            }
          }
        }
        
        .activity-info {
          margin-bottom: 15px;
          
          .info-item {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            font-size: 14px;
            color: #606266;
            
            .el-icon {
              margin-right: 5px;
              font-size: 16px;
            }
          }
        }
        
        .activity-actions {
          display: flex;
          justify-content: space-between;
        }
      }
    }
  }
  
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}
</style> 